package com.kyub.spring.gears.web;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.kyub.spring.gears.model.PojoRegistry;
import com.kyub.spring.gears.model.PojoDescriptor;
import com.kyub.spring.gears.introspect.PojoDescriptorFactory;
import com.kyub.spring.gears.services.DaoService;

import javax.naming.ConfigurationException;
import java.util.Collection;
import java.util.HashMap;


@Component 
public class ControllerHelper {

    @Autowired
    private PojoRegistry pojoRegistry;

    @Autowired
    private CrudControllerConfig crudConfig;

    private static PojoDescriptorFactory factory;

    public ModelAndView buildModelAndView(final Class classParam) throws ConfigurationException {

        ModelAndView model = new ModelAndView();
        checkFactory();
        PojoDescriptor pojoDescriptor =factory.buildDescriptorByClass(classParam);

         model.addObject("pojoDescriptor", pojoDescriptor);
         model.addObject(ControllerAncestor.GEARS_RESTFULL_PREFIX,crudConfig.getResfullPrefix());
        return model;

    }

    private void checkFactory() {
        if(factory == null){
              factory = new PojoDescriptorFactory(pojoRegistry);
        }
    }

    public ModelAndView buildModelAndView(final Object objectParam) throws ConfigurationException {

       ModelAndView model = buildModelAndView(objectParam.getClass());
       model.addObject(CrudController.COMMAND_POJO_NAME,objectParam);
       return model;

    }

    public void addRelated(ModelAndView modelAndView, String key, Collection data){

         if(!modelAndView.getModel().containsKey(CrudController.RELATED)){
              final HashMap hashMap = new HashMap();
             modelAndView.addObject(CrudController.RELATED,hashMap);
        }

        ((HashMap)modelAndView.getModel().get(CrudController.RELATED)).put(key,data);

    }

    public void addGearsBinder(WebDataBinder binder, Class classParam, DaoService service) throws ConfigurationException {
         checkFactory();
        final PropertyEditorBuilder pb = new PropertyEditorBuilder();
        binder.registerCustomEditor(classParam, pb.buildPropertyEditorSupport(factory.buildDescriptorByClass(classParam),service));



    }


}
